/*
 * karehatasksendpost.cpp
 *
 *  Created on: Oct 1, 2011
 *      Author: anonovermind <anonovermind@gmail.com>
 */

#include "karehatasksendpost.h"
#include "karehaagent.h"

namespace Wishmaster {

KarehaTaskSendPost::KarehaTaskSendPost(const PostDescriptor& post, const QString& captcha,
		Wishmaster2::Network::RequestManager* requestManager, const QString& msg, KarehaAgent* agent) :
			TaskSendPost(post, captcha, requestManager, msg),
			m_post(post),
			m_captcha(captcha),
			m_agent(agent)
{

}

KarehaTaskSendPost::~KarehaTaskSendPost() {
}

ThreadId KarehaTaskSendPost::threadId() const
{
	return m_threadId;
}

Wishmaster2::Network::RequestPtr KarehaTaskSendPost::makeRequest(const PostDescriptor& post, const QString& captcha,
			Wishmaster2::Network::RequestManager* requestManager)
{
	m_threadId = post.parent_thread;
	QString karehascript = m_agent->property("karehascript").toString();
	karehascript.replace("%BOARD%", m_threadId.boardId());

	Wishmaster2::Network::Url url((QString("http://") + m_threadId.chanName() + karehascript).toStdString());
	Wishmaster2::Network::RequestPtr request = requestManager->createRequest(url);
	request->setParameter("http:method", "POST");

	request->setParameter("task", "post");
	request->setParameter("name", "");
	request->setParameter("link", "");
	if(!post.parent_thread.threadStringId().isEmpty())
		request->setParameter("thread", std::string(post.parent_thread.threadStringId().toUtf8().constData()));
	request->setParameter(m_agent->property("field1name").toString().toStdString(), std::string(post.name.toUtf8().constData()));
	request->setParameter(m_agent->property("field2name").toString().toStdString(), std::string(post.email.toUtf8().constData()));
	request->setParameter("markup", "waka");
	request->setParameter(m_agent->property("field4name").toString().toStdString(), std::string(post.text.toUtf8().constData()));
	m_agent->addAttachments(request, post.attachments.count() > 0 ? post.attachments.at(0) : AttachmentDescriptor(), "file");
	if(!m_agent->property("nopostcaptcha").toBool())
		request->setParameter("captcha", std::string(captcha.toUtf8().constData()));
	request->setParameter("password", std::string(post.password.toUtf8().constData()));

	m_request = request;

	return request;
}

void KarehaTaskSendPost::onRequestDone()
{
	QByteArray arr(m_request->content()->data(), m_request->content()->size());
	emit result(this, arr, QString(m_request->contentType().c_str()));
}

} /* namespace Wishmaster */
